// 6. 支付服务管理器（更实际的使用场景）
package com.example.spi;

import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

public class PaymentServiceManager {
    private static final Map<String, PaymentService> paymentServices = new ConcurrentHashMap<>();
    
    static {
        // 在静态代码块中初始化所有支付服务
        loadPaymentServices();
    }
    
    private static void loadPaymentServices() {
        ServiceLoader<PaymentService> serviceLoader = ServiceLoader.load(PaymentService.class);
        for (PaymentService service : serviceLoader) {
            paymentServices.put(service.getPaymentType().toLowerCase(), service);
            System.out.println("注册支付服务: " + service.getPaymentType());
        }
    }
    
    public static PaymentService getPaymentService(String paymentType) {
        return paymentServices.get(paymentType.toLowerCase());
    }
    
    public static void executePayment(String paymentType, double amount) {
        PaymentService service = getPaymentService(paymentType);
        if (service != null) {
            service.pay(amount);
        } else {
            System.out.println("不支持的支付方式: " + paymentType);
        }
    }
    
    public static void listAvailablePaymentMethods() {
        System.out.println("可用的支付方式:");
        paymentServices.keySet().forEach(type -> System.out.println("- " + type));
    }
    
    // 测试方法
    public static void main(String[] args) {
        System.out.println("=== 支付服务管理器演示 ===");
        
        // 列出所有可用支付方式
        listAvailablePaymentMethods();
        
        // 执行不同的支付
        System.out.println("\n执行支付测试:");
        executePayment("alipay", 150.0);
        executePayment("wechatpay", 250.0);
        executePayment("unionpay", 350.0);
        executePayment("unknown", 100.0); // 测试不存在的支付方式
    }
}
